package com.fgba.express.security;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fgba.express.comm.result.Result;
import com.fgba.express.util.BeanContextUtil;
import com.fgba.express.util.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author fgba
 */
@Component
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String name = authentication.getName();
        JwtUtils jwtUtils = BeanContextUtil.getBean(JwtUtils.class);
        // 生成jwt返回
        String jwt = jwtUtils.generateToken(name);

        response.setHeader(jwtUtils.getHeader(), jwt);
        Result<Object> result = Result.success();

        outputStream.write(new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }


}
